# -*- coding:utf-8 -*-

from typing import List
from sqlalchemy.ext.asyncio import AsyncSession

from config.constant import CommonConstant
from exceptions.exception import ServiceException
from utils.common_util import CamelCaseUtil, export_list2excel
from module_admin.entity.vo.sys_table_vo import SysTablePageModel
from module_admin.service.sys_table_service import SysTableService
from utils.page_util import PageResponseModel
from module_doc.dao.bg_file_category_dao import BgFileCategoryDao
from module_doc.entity.do.bg_file_category_do import BgFileCategory
from module_doc.entity.vo.bg_file_category_vo import BgFileCategoryPageModel, BgFileCategoryModel, BgFileCategoryAddModel


class BgFileCategoryService:
    """
    用户管理模块服务层
    """

    @classmethod
    async def get_bg_file_category_list(cls, query_db: AsyncSession, query_object: BgFileCategoryPageModel, data_scope_sql: str, is_page=True) -> [list | PageResponseModel]:
        bg_file_category_list = await BgFileCategoryDao.get_bg_file_category_list(query_db, query_object, data_scope_sql, is_page=is_page)
        return bg_file_category_list

    @classmethod
    async def get_bg_file_category_by_id(cls, query_db: AsyncSession, bg_file_category_id: int) -> BgFileCategoryModel:
        bg_file_category = await  BgFileCategoryDao.get_by_id(query_db, bg_file_category_id)
        bg_file_category_model = BgFileCategoryModel(**CamelCaseUtil.transform_result(bg_file_category))
        return bg_file_category_model


    @classmethod
    async def add_bg_file_category(cls, query_db: AsyncSession, query_object: BgFileCategoryAddModel) -> BgFileCategoryModel:

        if not await cls.__check_category_name_unique_services(query_db, query_object):
            raise ServiceException(message=f'新增分类{query_object.category_name}失败，分类名称已存在')
        parent_info = await BgFileCategoryDao.get_by_id(query_db, query_object.parent_id)
        if not parent_info:
            raise ServiceException(message="父分类不存在")
        if parent_info.status != CommonConstant.DEPT_NORMAL:
            raise ServiceException(message=f'分类{parent_info.category_name}停用，不允许新增')
        if parent_info.ancestors is not None:
            query_object.ancestors = f'{parent_info.ancestors},{parent_info.id}'
        else:
            query_object.ancestors = f'{parent_info.id}'
        bg_file_category_model = await BgFileCategoryDao.add_bg_file_category(query_db, query_object)
        return bg_file_category_model

    @classmethod
    async def __check_category_name_unique_services(cls, query_db: AsyncSession, query_object: BgFileCategoryAddModel) -> [bool]:
        category_id = -1 if query_object.id is None else query_object.id
        category = await BgFileCategoryDao.get_bg_file_category_list(
            query_db, BgFileCategoryPageModel(categoryName=query_object.category_name, parentId=query_object.parent_id)
        )
        if category_id and len(category) > 0 and category[0].id != category_id:
            return CommonConstant.NOT_UNIQUE
        return CommonConstant.UNIQUE


    @classmethod
    async def update_bg_file_category(cls, query_db: AsyncSession, query_object: BgFileCategoryModel) -> BgFileCategoryModel:
        bg_file_category = await BgFileCategoryDao.edit_bg_file_category(query_db, query_object)
        bg_file_category_model = BgFileCategoryModel(**CamelCaseUtil.transform_result(bg_file_category))
        return bg_file_category_model


    @classmethod
    async def del_bg_file_category(cls, query_db: AsyncSession, bg_file_category_ids: List[str]):
        await BgFileCategoryDao.del_bg_file_category(query_db, bg_file_category_ids)


    @classmethod
    async def export_bg_file_category_list(cls, query_db: AsyncSession, query_object: BgFileCategoryPageModel, data_scope_sql) -> bytes:
        bg_file_category_list = await BgFileCategoryDao.get_bg_file_category_list(query_db, query_object, data_scope_sql, is_page=False)
        filed_list = await SysTableService.get_sys_table_list(query_db, SysTablePageModel(tableName='bg_file_category'), is_page=False)
        filtered_filed = sorted(filter(lambda x: x["show"] == '1', filed_list), key=lambda x: x["sequence"])
        new_data = []
        for item in bg_file_category_list:
            mapping_dict = {}
            for fild in filtered_filed:
                if fild["prop"] in item:
                    mapping_dict[fild["label"]] = item[fild["prop"]]
            new_data.append(mapping_dict)
        binary_data = export_list2excel(new_data)
        return binary_data

    @classmethod
    async def get_bg_file_category_tree(cls, query_db: AsyncSession, query_object: BgFileCategoryPageModel = None) -> List[dict]:
        """
        获取文件分类树形结构
        """
        tree_data = await BgFileCategoryDao.get_bg_file_category_tree(query_db, query_object)
        return tree_data

    @classmethod
    async def get_bg_file_category_children(cls, query_db: AsyncSession, parent_id: int) -> List[dict]:
        """
        获取指定父分类下的子分类列表
        """
        children_data = await BgFileCategoryDao.get_bg_file_category_children(query_db, parent_id)
        return children_data